package com.hsh.config.jwt;


import com.alibaba.fastjson.JSON;
import com.hsh.tools.StrUtils;
import com.hsh.tools.handler.BusinessException;
import com.hsh.utils.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JWTFilter extends BasicHttpAuthenticationFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("~~~~~~~~~~~~~~~~~对跨域提供支持==>JWTFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

//        System.out.println("httpServletRequest.getMethod(): " + httpServletRequest.getMethod());
//        System.out.println("RequestMethod.OPTIONS.name(): " + RequestMethod.OPTIONS.name());
//        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
//        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
//            httpServletResponse.setStatus(HttpStatus.OK.value());
//            return false;
//        }
        return super.preHandle(request, response);
    }

    /**
     * 认证之前执行该方法
     */
    /**
     * 这里我们详细说明下为什么最终返回的都是true，即允许访问
     * 例如我们提供一个地址 GET /article
     * 登入用户和游客看到的内容是不同的
     * 如果在这里返回了false，请求会被直接拦截，用户看不到任何东西
     * 所以我们在这里返回true，Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入
     * 如果有些资源只有登入用户才能访问，我们只需要在方法上面加上 @RequiresAuthentication 注解即可
     * 但是这样做有一个缺点，就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法)，但实际上对应用影响不大
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("~~~~~~~~~~~~~~~~~认证之前执行该方法==>JWTFilter");
        Subject subject = SecurityUtils.getSubject();
        return null != subject && subject.isAuthenticated();
    }


    /**
     * 认证未通过执行该方法
     * <p>
     * 这个方法是{isAccessAllowed()返回false}之后执行的
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        System.out.println("~~~~~~~~~~~~~~~~~认证未通过执行该方法==>JWTFilter");
        // 1、检查请求头中是否含有token
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Authorization");
        // 2、 没有token
        if (StrUtils.isEmpty(token)) {
            //"Token无效，您无权访问该接口"
//            logger.error("Token无效，您无权访问该接口【无token】--JWTFilter");
            responseTokenError(response, "Token无效，您无权访问该接口【无token】--JWTFilter");
            return false;
        }
        // 3、存在token，进行校验
        JWTToken jwtToken = new JWTToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
        } catch (BusinessException | AuthenticationException e) {
            responseTokenError(response, "Token认证失败，请重新登录！");
            return false;
        }
        return true;
    }


    /**
     * 无需转发，直接返回Response信息 Token认证错误
     */
    private void responseTokenError(ServletResponse response, String msg) {
        System.out.println("~~~~~~~~~~~~~~~~~无需转发，直接返回Response信息 Token认证错误==>JWTFilter");
//        logger.error("~~~~~~~~~~~~~~~~~无需转发，直接返回Response信息 Token认证错误==>JWTFilter");
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            String data = JSON.toJSONString(ResultCode.getResult(401, msg));
            out.write(data);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
}

